<?php

class PermissionsController extends \Phalcon\Mvc\Controller {

    public function indexAction() {
        $permissions = Permissions::find();
        $this->view->permissions = $permissions;
    }

    public function editAction() {
        if ($this->request->isPost()) {
            $permissions = $this->request->getPost('permission');
            foreach ($permissions as $key => $value) {
                $permission = new Permissions();
                $permission->controller = strtolower($key);
                $permission->roles = implode(',', $value);
                $permission->save();
            }
        }
        $files = scandir(dirname(__FILE__), 0);
        $permissions = array();
        foreach ($files as $file) {
            if (strpos($file, 'Controller.php')) {
                $controllerName = substr($file, 0, strpos($file, 'Controller.php'));
                $permission = Permissions::findFirstByController($controllerName);
                $permissions[] = array(
                    'controller' => $controllerName,
                    'roles' => $permission ? explode(',',$permission->roles) : array(),
                );
            }
        }

        $this->view->permissions = $permissions;
        $roles = Roles::find();
        $this->view->roles = $roles;
    }

}
